<?php

class FeaturedProgrammes extends RecordObject {
	public static function getTableName() {
		return "featured_programmes";
	}
	public function getPrimaryKey() {
		return array('id');
	}
}

class Freezone extends RecordObject {
	public static function getTableName() {
		return "freezone";
	}
	public function getPrimaryKey() {
		return array('id');
	}
}

class Mpm extends RecordObject {
	public static function getTableName() {
		return "mpm";
	}
	public function getPrimaryKey() {
		return array('id');
	}
}

class PortalWebServiceDataMytvplus extends PortalWebServiceDataBase{
	protected $db_handle;

	// {{{ public function __construct($config, $timeless, $time_now)
	public function __construct($config, $timeless, $time_now)
	{
		parent::__construct($config, $timeless, $time_now);
		$this->createReadableRecordFactory();
	}
	// }}}

	// {{{ private function createReadableRecordFactory()
	private function createReadableRecordFactory()
	{
		$readers = array ();
		foreach ($this->server_config->mytvplus_admin_db->readers->reader as $reader) {
			$readers[] = array(
				'host' => (string) $reader->dbhost,
				'user' => (string) $reader->dbuser,
				'pass' => (string) $reader->dbpass,
				'name' => (string) $reader->dbname
			);
		}
		$db = $readers[array_rand($readers)];
		$this->db_handle = new ReadableRecordFactory($db['host'], $db['user'], $db['pass'], $db['name']);
	}
	// }}}

	/*
		case 'mytvplus.chapter':
		case 'mytvplus.episode':
		case 'mytvplus.programme':
		case 'mytvplus.featureprogrammes':
		case 'mytvplus.featureepisodes ':
	*/

	// {{{ public function _chapters($ids,$lang='zh',$offset=0,$limit=10,array $sort=array('online_time'=>'asc'),$format='json')
	public function _chapters($ids,$lang='zh',$offset=0,$limit=10,array $sort=array('online_time'=>'desc'),$format='json')
	{
		$lang = $this->__check_lang($lang);
		$format = $this->__check_format($format);

		$data = array('total'=>0,'size'=>0,'offset'=>$offset,'limit'=>$limit,'sort'=>$sort,'data'=>array());
		if(!($ids)) return ($format=='xml' ? CommonUtils::arrayToXml($data) : $data);
		$query = 'id:('.str_replace(',',' ',$ids).')';
		//$chapter_data = $this->getDataByQuery('Chapter',$query,$offset,$limit,$sort);
		//$chapter_data = $this->getDataByQuery('Chapter',$query,$offset,$limit,array('id'=>'desc'));
		$chapter_data = $this->getDataByQuery('Chapter',$query,$offset,$limit);
		if(empty($chapter_data)) return ($format=='xml' ? CommonUtils::arrayToXml($data) : $data);

		$video_ids = $category_ids = array();
		foreach($chapter_data->docs as $row){
			if(!in_array($row->video_id, $video_ids))
				$video_ids[] = $row->video_id;
			if(!in_array($row->primary_category_id, $category_ids))
				$category_ids[] = $row->primary_category_id;
		}
		$query = 'id:('.implode(' ',$video_ids).')';
		$video_raw_data = $this->getDataByQuery('Video',$query,0,$limit);
		foreach($video_raw_data->docs as $row){
			$video_data[$row->id] = (array) $row;
		}
		$query = 'id:('.implode(' ',$category_ids).')';
		$category_data = $this->getFormatDataByQuery('Category', $query, 0, $limit, array(), $lang);

		$programme_ids = $folder_ids = array();
		foreach($video_data as $row){
			if(!in_array($row['programme_id'], $programme_ids))
				$programme_ids[] = $row['programme_id'];
			$folder_id = explode(',',$row['folder_list']);
			foreach($folder_id as $fid){
				if(!in_array($fid, $folder_ids))
					$folder_ids[] = $fid;
			}
		}
		$query = 'id:('.implode(' ',$programme_ids).')';
		$programme_data = $this->getFormatDataByQuery('Programme',$query,0,$limit);
		$query = 'id:('.implode(' ',$folder_ids).')';
		$folder_data = $this->getFormatDataByQuery('Folder', $query, 0, $limit, array(), $lang);

		$data['total'] = $chapter_data->numFound;
		$data['size']  = count($chapter_data->docs);
		foreach($chapter_data->docs as $row){
			$folder_id = explode(',',$video_data[$row->video_id]['folder_list']);
			$folder_list = $this->formatMytvplusFolderData($folder_data['data'], $folder_id);
			$data['data'][$row->id] = $this->formatMytvplusChapterData((array) $row,$video_data[$row->video_id],$folder_list,$programme_data['data'][$video_data[$row->video_id]['programme_id']],$category_data['data'][$row->primary_category_id],$lang);
		}
		return ($format=='xml' ? CommonUtils::arrayToXml($data) : $data);
	}
	// }}}

	// {{{ public function _chapter($id,$lang='zh',$format='json')
	public function _chapter($id,$lang='zh',$format='json')
	{
		$lang = $this->__check_lang($lang);
		$format = $this->__check_format($format);

		$chapter_data = (array) $this->getDataById('Chapter',$id);
		if(empty($chapter_data)) return null;

		$video_data = (array) $this->getDataById('Video',$chapter_data['video_id']);
		if(empty($video_data)) return null;

		//$episode_data = (array) $this->getDataById('Episode',$video_data['episode_id']);
		$query = 'id:('.str_replace(',',' ',$video_data['folder_list']).')';
		$folder_data = $this->getFormatDataByQuery('Folder', $query, 0, 999999999, array(), $lang);
		$folder_id = explode(',',$video_data['folder_list']);
		$folder_list = $this->formatMytvplusFolderData($folder_data['data'], $folder_id);

		$programme_data = $this->getFormatDataById('Programme',$video_data['programme_id'],$lang);
		$category_data = $this->getFormatDataById('Category', $chapter_data['primary_category_id'], $lang);

		$data = $this->formatMytvplusChapterData($chapter_data,$video_data,$folder_list,$programme_data,$category_data,$lang);
		return ($format=='xml' ? CommonUtils::arrayToXml($data) : $data);
	}
	// }}}

	// {{{ public function _episodes($ids,$lang='zh',$offset=0,$limit=10,array $sort=array('online_time'=>'asc'),$format='json')
	public function _episodes($ids,$lang='zh',$offset=0,$limit=10,array $sort=array('online_time'=>'asc'),$format='json') {
		$lang = $this->__check_lang($lang);
		$format = $this->__check_format($format);

		$data = array('total'=>0,'size'=>0,'offset'=>$offset,'limit'=>$limit,'sort'=>$sort,'data'=>array());

		if(!($ids)) return ($format=='xml' ? CommonUtils::arrayToXml($data) : $data);

		$query = 'id:('.str_replace(',',' ',$ids).')';
		$episode_data = $this->getDataByQuery('Episode',$query,$offset,$limit,$sort);
		if(empty($episode_data)) return ($format=='xml' ? CommonUtils::arrayToXml($data) : $data);

		$programme_ids = $episode_ids = array();
		foreach($episode_data->docs as $row){
			if(!in_array($row->id, $episode_ids))
				$episode_ids[] = $row->id;
			if(!in_array($row->programme_id, $programme_ids))
				$programme_ids[] = $row->programme_id;
		}

		$query = 'id:('.implode(' ',$programme_ids).')';
		$programme_data = $this->getFormatDataByQuery('Programme', $query, 0, $limit, array(), $lang);

		$video_data = array();
		$query = 'episode_id:('.implode(' ',$episode_ids).') AND folder_type_path:regular';
		$video_raw_data = $this->getDataByQuery('Video',$query,0,999999999);
		if (!empty($video_raw_data)){
			foreach($video_raw_data->docs as $row){
				//$video_data[$row->episode_id][$row->id] = (array) $row;
				$video_data[$row->episode_id] = (array) $row;
			}
		}

		$folder_ids = array();
		$folder_data = array();
		if (!empty($video_data)){
			foreach($video_data as $row){
				$folder_id = explode(',',$row['folder_list']);
				foreach($folder_id as $fid){
					if(!in_array($fid, $folder_ids))
						$folder_ids[] = $fid;
				}
			}
			$query = 'id:('.implode(' ',$folder_ids).')';
			$folder_data = $this->getFormatDataByQuery('Folder', $query, 0, 999999999, array(), $lang);
		}

		$category_ids = array();
		foreach($programme_data['data'] as $idx => $row){
			if(!in_array($row['primary_category_id'], $category_ids))
				$category_ids[] = $row['primary_category_id'];
		}
		$query = 'id:('.implode(' ',$category_ids).')';
		$category_data = $this->getFormatDataByQuery('Category', $query, 0, $limit, array(), $lang);

		$data['total'] = $episode_data->numFound;
		$data['size']  = count($episode_data->docs);
		foreach($episode_data->docs as $row) {
			$folder_list = array();
			if (!empty($video_data)) {
				$folder_id = explode(',',$video_data[$row->id]['folder_list']);
				$folder_list = $this->formatMytvplusFolderData($folder_data['data'], $folder_id);
			}
			if (!array_key_exists($row->id,$video_data)) continue;  
			$data['data'][$row->id] = $this->formatMytvplusEpisodeData((array) $row,$video_data[$row->id],$folder_list,$programme_data['data'][$row->programme_id],$category_data['data'][$programme_data['data'][$row->programme_id]['primary_category_id']],$lang);
		}
		return ($format=='xml' ? CommonUtils::arrayToXml($data) : $data);
	}
	// }}}

	// {{{ public function _episode($id,$lang='zh',$format='json')
	public function _episode($id,$lang='zh',$format='json')
	{
		$lang = $this->__check_lang($lang);
		$format = $this->__check_format($format);

		$episode_data = (array) $this->getDataById('Episode',$id);
		if (empty($episode_data)) return null;

		$query = 'episode_id:'.$episode_data['id'];
		$video_data = $this->getDataByQuery('Video',$query);
		if(!empty($video_data->numFound)){
			$video_data = (array) $video_data->docs[0];

			$query = 'id:('.str_replace(',',' ',$video_data['folder_list']).')';
			$folder_data = $this->getFormatDataByQuery('Folder', $query, 0, 999999999, array(), $lang);
			$folder_id = explode(',',$video_data['folder_list']);
			$folder_list = $this->formatMytvplusFolderData($folder_data['data'], $folder_id);
		} else {
			$video_data = array();
			//$folder_data = array();
			$folder_list = array();
		}
		$programme_data = $this->getFormatDataById('Programme',$episode_data['programme_id'],$lang);
		$category_data = $this->getFormatDataById('Category', $programme_data['primary_category_id'], $lang);

		$data = $this->formatMytvplusEpisodeData($episode_data,$video_data,$folder_list,$programme_data,$category_data,$lang);
		return ($format=='xml' ? CommonUtils::arrayToXml($data) : $data);
	}
	// }}}

	// {{{ public function _programmes($paths,$lang='zh',$offset=0,$limit=10,array $sort=array('online_time'=>'asc'),$format='json')
	public function _programmes($paths,$lang='zh',$offset=0,$limit=10,array $sort=array('online_time'=>'desc'),$format='json')
	{
		$lang = $this->__check_lang($lang);
		$format = $this->__check_format($format);
		$data = array('total'=>0,'size'=>0,'offset'=>$offset,'limit'=>$limit,'sort'=>$sort,'data'=>array());

		if(!($paths)) return ($format=='xml' ? CommonUtils::arrayToXml($data) : $data);

		$query = 'path:('.str_replace(',',' ',$paths).')';
		$data = $this->getFormatDataByQuery('Programme',$query,$offset,$limit,$sort,$lang);
		//if(empty($data)) return null;

		$category_ids = array();
		foreach($data['data'] as $idx => $row){
			if(!in_array($row['primary_category_id'], $category_ids))
				$category_ids[] = $row['primary_category_id'];
			$programme_ids[$idx] = $idx;
		}

		if (empty($programme_ids)) return ($format=='xml' ? CommonUtils::arrayToXml($data) : $data);

		$query = 'id:('.implode(' ',$category_ids).')';
		$category_data = $this->getFormatDataByQuery('Category', $query, 0, $limit, array(), $lang);

		$query = 'programme_id:('.implode(' ',$programme_ids).')';
		//$episode_data = $this->getDataByQuery('Episode',$query,0,999999999);
		$query = '-episode_id:(0) AND programme_id:('.implode(' ',$programme_ids).')';
		$query .=  " AND (folder_type_path:regular) ";
		$query .= " AND subscription_online_time:[* TO ".strtotime("NOW")."] AND subscription_offline_time:[".strtotime("NOW")." TO *]";	
		$video_data = $this->getDataByQuery('Video',$query,0,999999999);
		//$episode_ids = array();

		//foreach ($video_data->docs as $vid) $episode_ids[] = $vid->episode_id;
		$episode_data = $video_data;
		//$episode_data = $this->getDataByQuery('Episode',$query,0,999999999);
		$programme_epi = array();

		if(!empty($episode_data)) {
			foreach($episode_data->docs as $epi){
				if (!isset($programme_epi[$epi->programme_id])) {
					$programme_epi[$epi->programme_id] = array(
						'minEpi' => '',
						'maxEpi' => '',
						'latest_episode_time' => ''
					);
				}
				if ($programme_epi[$epi->programme_id]['minEpi'] == ''){
					$programme_epi[$epi->programme_id] = array(
						'minEpi'=>$epi->onair_episode_no,
						'maxEpi'=>$epi->onair_episode_no,
						//'latest_episode_time'=>$epi->online_time
						'latest_episode_time'=>$epi->subscription_online_time
					);
				}
				if ($epi->onair_episode_no < $programme_epi[$epi->programme_id]['minEpi'])
					$programme_epi[$epi->programme_id]['minEpi'] = $epi->onair_episode_no;
				if ($epi->onair_episode_no > $programme_epi[$epi->programme_id]['maxEpi'])
					$programme_epi[$epi->programme_id]['maxEpi'] = $epi->onair_episode_no;
				if ($epi->subscription_online_time > $programme_epi[$epi->programme_id]['latest_episode_time'])
					$programme_epi[$epi->programme_id]['latest_episode_time'] = $epi->subscription_online_time;
			}
		}

		foreach($data['data'] as $idx => $row){
			if (!isset($programme_epi[$idx])) {
				$programme_epi[$idx] = array(
					'minEpi' => '',
					'maxEpi' => '',
					'latest_episode_time' => $row['last_episode_time_onair']
				);
			}
			$data0 = $this->formatMytvplusProgrammeData($data['data'][$idx],$category_data['data'][$row['primary_category_id']],$programme_epi[$idx],$lang);
			$data['data'][$idx] = $data0;
		}
		return ($format=='xml' ? CommonUtils::arrayToXml($data) : $data);
	}
	// }}}

	// {{{ public function _programme($id,$lang='zh',$format='json')
	public function _programme($id,$lang='zh',$format='json')
	{
		$lang = $this->__check_lang($lang);
		$format = $this->__check_format($format);

		$programme_data = $this->getFormatDataById('Programme',$id, $lang);
		if(empty($programme_data)) return null;

		$category_data  = $this->getFormatDataById('Category', $programme_data['primary_category_id'], $lang);

		$query = "programme_id:$id";
		$rs = $this->getDataByQuery('Episode',$query);
		if(!empty($rs->numFound)) {
			foreach($rs->docs as $epi){
				$episode_data = array(
					'minEpi' => '',
					'maxEpi' => '',
					'latest_episode_time' => '',
				);
				if ($epi->offline_time >= time()) {
					if ($episode_data['minEpi'] == '')
						$episode_data = array(
							'minEpi'=>$epi->onair_episode_no,
							'maxEpi'=>$epi->onair_episode_no,
							'latest_episode_time'=>$epi->online_time
						);
					if ($epi->onair_episode_no < $episode_data['minEpi'])
						$episode_data['minEpi'] = $epi->onair_episode_no;
					if ($epi->onair_episode_no > $episode_data['maxEpi'])
						$episode_data['maxEpi'] = $epi->onair_episode_no;
					if ($epi->online_time > $episode_data['latest_episode_time'])
						$episode_data['latest_episode_time'] = $epi->online_time;
				}
			}
		}

		$data = $this->formatMytvplusProgrammeData($programme_data,$category_data,$episode_data,$lang);
		return ($format=='xml' ? CommonUtils::arrayToXml($data) : $data);
	}
	// }}}

	// {{{ public function _featureprogrammes($lang='zh',$offset=0,$limit=10,$format='json')
	public function _featureprogrammes($lang='zh',$offset=0,$limit=10,$format='json')
	{
		$lang = $this->__check_lang($lang);
		$format = $this->__check_format($format);

		$featprog = (array) $this->db_handle->findAll('FeaturedProgrammes');
		foreach($featprog as $row){
			$path = explode('/',$row->path);
			$programme_paths[] = $path[2];
		}
		$data = PortalWebServiceDataMytvplus::_programmes(implode(',',$programme_paths),$lang,$offset,$limit);

		return ($format=='xml' ? CommonUtils::arrayToXml($data) : $data);
	}
	// }}}

	// {{{ public function _featureepisodes($lang='zh',$offset=0,$limit=10,$format='json')
	public function _featureepisodes($lang='zh',$offset=0,$limit=10,$format='json')
	{
		$lang = $this->__check_lang($lang);
		$format = $this->__check_format($format);

		$freezone = (array) $this->db_handle->findAll('Freezone');
		foreach($freezone as $row){
			$path = explode('/',$row->path);
			if (empty($path[3])){
				$programme_paths[] = $path[2];
			}else{
				$video_ids[] = $path[3];
			}
		}

		if (!empty($programme_paths)) {
			$query = 'path:('.implode(' ',$programme_paths).')';
			$data = $this->getFormatDataByQuery('Programme',$query,0,999999999);
			$programme_ids = array();
			foreach($data['data'] as $idx => $row){
				$programme_ids[] = $idx;
			}

			$query = 'programme_id:('.implode(' ',$programme_ids).')';
			$data = $this->getFormatDataByQuery('Episode',$query,0,999999999);
			$episode_ids = array();
			foreach($data['data'] as $idx => $row){
				$episode_ids[] = $idx;
			}
		}

		$query = 'id:('.implode(' ',$video_ids).')';
		$data = $this->getDataByQuery('Video',$query,0,999999999);
		foreach($data->docs as $row){
			$episode_ids[] = $row->episode_id;
		}

		$data = PortalWebServiceDataMytvplus::_episodes(implode(',',$episode_ids),$lang,$offset,$limit);

		return ($format=='xml' ? CommonUtils::arrayToXml($data) : $data);
	}
	// }}}

	// {{{ public function _mpm($lang='zh',$format='json')
	public function _mpm($lang='zh',$format='json')
	{
		$lang = $this->__check_lang($lang);
		$format = $this->__check_format($format);

		$current_datetime = time();
		$mpm = (array) $this->db_handle->findAll('Mpm');
		foreach($mpm as $row){
			if (($current_datetime >= $row->online_datetime || $row->online_datetime == 0) && ($current_datetime <= $row->offline_datetime || $row->offline_datetime == 0)){
				$path = explode('/',$row->path);
				if ($row->type == 'programme'){
					$programme_paths[] = $path[2];
				} else if ($row->type == 'episode'){
					//$video_ids[] = $path[3];
					$episode_ids[] = $path[3];
				//} else if ($row->type == 'chapter'){
				//	$video_ids[] = $path[3];
				}
			}
		}

		$programme_ids = array();
		if (!empty($programme_paths)) {
			$query = 'path:('.implode(' ',$programme_paths).')';
			$data = $this->getFormatDataByQuery('Programme',$query,0,999999999);
			$programme_ids = array();
			if(!empty($data)){
				foreach($data['data'] as $idx => $row){
					$programme_ids[$row['path']] = $idx;
				}
			}
		}
/*
		$episode_ids = array();
		if (!empty($video_ids)) {
			$query = 'id:('.implode(' ',$video_ids).')';
			$data = $this->getDataByQuery('Video',$query,0,999999999);
			if(!empty($data)){
				foreach($data->docs as $row){
					$episode_ids[$row->id] = $row->episode_id;
				}
			}
		}
*/
		$programme_data = PortalWebServiceDataMytvplus::_programmes(implode(',',$programme_paths),$lang,0,999999999);
		$episode_data = PortalWebServiceDataMytvplus::_episodes(implode(',',$episode_ids),$lang,0,999999999);
		foreach($episode_data['data'] as $idx => $row){
			$episode_data['data'][$row['epi_id']] = $row;
			//unset($episode_data['data'][$idx]);
		}
		//$chapter_data = PortalWebServiceDataMytvplus::_chapters(implode(',',$chapter_ids),$lang,0,999999999);

		$data = array();
		foreach($mpm as $row){
			if (($current_datetime >= $row->online_datetime || $row->online_datetime == 0) && ($current_datetime <= $row->offline_datetime || $row->offline_datetime == 0)){
				$path = explode('/',$row->path);
				if ($row->type == 'programme'){
					if(array_key_exists($programme_ids[$path[2]], $programme_data['data']))
						$data[] = $programme_data['data'][$programme_ids[$path[2]]];
				} else if ($row->type == 'episode'){
					//if(array_key_exists($episode_ids[$path[3]], $episode_data['data']))
					//	$data[] = $episode_data['data'][$episode_ids[$path[3]]];
					if(array_key_exists($path[3], $episode_data['data']))
						$data[] = $episode_data['data'][$path[3]];
				//} else if ($row->type == 'chapter'){
				//	$video_ids[] = $path[3];
				}
			}
		}

		return ($format=='xml' ? CommonUtils::arrayToXml($data) : $data);
	}
	// }}}

	// {{{ protected function formatMytvplusFolderData($folder_data,$folder_ids)
	protected function formatMytvplusFolderData($folder_data,$folder_ids)
	{
		foreach ($folder_ids as $fid) {
			$folder_list[] = array(
				'id' => $folder_data[$fid]['id'],
				'type' => $folder_data[$fid]['type'],
				'title' => $folder_data[$fid]['title'],
				'contains' => $folder_data[$fid]['contains']
			);
		}
		return $folder_list;
	}
	// }}}

	// {{{ protected function formatMytvplusChapterData($chapter_data,$video_data,$folder_list,$programme_data,$category_data,$lang)
	protected function formatMytvplusChapterData($chapter_data,$video_data,$folder_list,$programme_data,$category_data,$lang)
	{
		return array(
			'cat_id'=>$chapter_data['primary_category_id'],
			'cat_path'=>$category_data['path'],
			'cat_name'=>$category_data['title'],
			'prg_id'=>$video_data['programme_id'], //$episode_data['programme_id'],
			'prg_path'=>$programme_data['path'],
			'prg_title'=>$programme_data['title'],
			'video_id'=>$chapter_data['video_id'], //$video_data['id'],
			'chapter_id'=>$chapter_data['id'],
			'folders'=> $folder_list, 
			'online_datetime'=>$video_data['online_time'],
			'offline_datetime'=>$video_data['offline_time'],
			'subscription_online_datetime'=>$video_data['subscription_online_time'],
			'subscription_offline_datetime'=>$video_data['subscription_offline_time'],
			'time_onair'=>$video_data['first_time_onair'], //$episode_data['first_time_onair'],
			'image'=>json_decode($chapter_data['ii_data'], true), //$video_data['ii_data'],
			//'duration'=>strtotime($chapter_data['out_time']) - strtotime($chapter_data['in_time']), //$video_data['duration'],
			'duration'=>$chapter_data['out_time'] - $chapter_data['in_time'], //$video_data['duration'],
			'full_duration'=>$video_data['duration'],
			'in_time'=>$chapter_data['in_time'],
			'out_time'=>$chapter_data['out_time'],
			'tags'=>json_decode($chapter_data['tags'], true), //$video_data['tags'],
			'description'=>$chapter_data['description_'.$lang],
			'link'=>'/'.$category_data['path'].'/'.$programme_data['path'].'/'.$chapter_data['video_id'].'/'.$chapter_data['in_time'],
			'title'=>$chapter_data['title_'.$lang],
			'epi_num'=>$chapter_data['onair_episode_no'], //$episode_data['onair_episode_no'],
			'free'=>$chapter_data['subscription_free_flag']
		);
	}
	// }}}

	// {{{ protected function formatMytvplusEpisodeData($episode_data,$video_data,$folder_list,$programme_data,$category_data,$lang)
	protected function formatMytvplusEpisodeData($episode_data,$video_data,$folder_list,$programme_data,$category_data,$lang)
	{
		return array(
			'cat_id'=>$programme_data['primary_category_id'],
			'cat_path'=>$category_data['path'],
			'cat_name'=>$category_data['title'],
			'prg_id'=>$episode_data['programme_id'],
			'prg_path'=>$programme_data['path'],
			'prg_title'=>$programme_data['title'],
			'video_id'=>$video_data['id'],
			'folders' => $folder_list,
			'online_datetime'=>$video_data['online_time'],
			'offline_datetime'=>$video_data['offline_time'],
			'subscription_online_datetime'=>$video_data['subscription_online_time'],
			'subscription_offline_datetime'=>$video_data['subscription_offline_time'],
			'first_time_onair'=>$video_data['first_time_onair'],
			'time_onair'=>$video_data['first_time_onair'],
			//'time_onair'=>$episode_data['first_time_onair'],
			'image'=>json_decode($video_data['ii_data'], true),
			'duration'=>$video_data['duration'],
			'tags'=>json_decode($video_data['tags'], true),
			'description'=>$episode_data['description_'.$lang],
			'link'=>'/'.$category_data['path'].'/'.$programme_data['path'].'/'.$video_data['id'],
			'epi_id'=>$episode_data['id'],
			'epi_num'=>$episode_data['onair_episode_no'],
			'title'=>$episode_data['title_'.$lang],
			'rates'=>$episode_data['rates'],
			'views'=> (array_key_exists('total_view', $video_data))?$video_data['total_view']:0,
			'free'=>$episode_data['subscription_free_flag']
		);
	}
	// }}}

	// {{{ protected function formatMytvplusProgrammeData($programme_data,$category_data,$episode_data,$lang)
	protected function formatMytvplusProgrammeData($programme_data,$category_data,$episode_data,$lang)
	{
		return array(
			'id'=>$programme_data['id'],
			'cat_id'=>$programme_data['primary_category_id'],
			'cat_path'=>$category_data['path'],
			'cat_name'=>$category_data['title'],
			'available_episode'=>array('min'=>$episode_data['minEpi'],'max'=>$episode_data['maxEpi']),
			'meta_keywords'=>$programme_data['meta_keywords'],
			'meta_description'=>$programme_data['meta_description'],
			'forum_id'=>$programme_data['forum_id'],
			'number_of_episodes'=>$programme_data['number_of_episodes'],
			'casts'=>json_decode($programme_data['casts'], true),
			'tags'=>json_decode($programme_data['tags'], true),
			'prg_path'=>$programme_data['path'],
			'prg_title'=>$programme_data['title'],
			'starting_episode_no'=>$programme_data['starting_episode_no'],
			'nominal_duration'=>$programme_data['nominal_duration'],
			'first_network_code'=>$programme_data['first_network_code'],
			'production_start_date'=>$programme_data['production_start_date'],
			'blog_url'=>$programme_data['blog_url'],
			'created_at'=>$programme_data['created_at'],
			'modified_at'=>$programme_data['modified_at'],
			'online_datetime'=>$programme_data['online_time'],
			'offline_datetime'=>$programme_data['offline_time'],
			'first_episode_time_onair' => $programme_data['first_episode_time_onair'],
			'last_episode_time_onair' => $programme_data['last_episode_time_onair'],
			'latest_episode_time'=>$episode_data['latest_episode_time'],
			//'latest_episode_time'=>$programme_data['modified_at'],
			'ppv_country_allow_list' => $programme_data['ppv_country_allow_list'],
			'ppv_country_deny_list' => $programme_data['ppv_country_deny_list'],
			'subscription_country_allow_list' => $programme_data['subscription_country_allow_list'],
			'subscription_country_deny_list' => $programme_data['subscription_country_deny_list'],
			'description'=>$programme_data['description'],
			'channelInfoPremiere'=>$programme_data['channelInfoPremiere'],
			'fact_background'=>$programme_data['fact_background'],
			'banner_image'=>$programme_data['banner_image'],
			'key_art_image'=>json_decode($programme_data['key_art_image'], true),
			'first_time_onair'=>$programme_data['first_time_onair'],
			'free'=>NULL
		);
	}
	// }}}
}
